﻿using System.Windows;
using SHomeWorkshop.LunarPresentation.Dialogs;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void EditBaseText(LunarPresentation.Expressions.BaseText curEx,
            ModifingItem mi = null, bool editingCommentText = false, string newText = null)
        {
            LunarPresentation.Expressions.BaseText btx
                = curEx as LunarPresentation.Expressions.BaseText;

            MainWindow mainWindow = curEx.Editor.ParentWindow;

            BaseTextEditor bte = new BaseTextEditor();

            #region 废弃代码
            //if (mainWindow.WindowState == WindowState.Maximized)
            //{
            //if (mainWindow.tbtnAutoLocationBaseTextEditor.IsChecked == true)
            //{
            //    bte.Top = 0;
            //    bte.Width = 440;
            //    bte.Left = mainWindow.ActualWidth - 448;
            //}
            //else
            //{
            //最大化主窗口，且未锁定编辑器状态下的编辑操作
            //bte.Width = mainWindow.ActualWidth - 80;
            //bte.Left = (mainWindow.ActualWidth - bte.Width) / 2;
            //bte.Height = 100;
            //bte.Top = mainWindow.ActualHeight - bte.Height - 86;//86包含状态条、滚动条的高度。

            //如果正在编辑的文本块被挡住，就自动向上滚动。
            //AutoScrollBaseText(bte);
            //}
            //}
            //else
            //{
            //if (mainWindow.tbtnAutoLocationBaseTextEditor.IsChecked == true)
            //{
            //    bte.WindowStartupLocation = WindowStartupLocation.Manual;
            //    bte.Width = 640;
            //    bte.Left = mainWindow.Left + mainWindow.ActualWidth - bte.Width;
            //    bte.Top = mainWindow.Top;
            //}
            //else
            //{
            //非最大化状态下编辑
            //bte.Width = mainWindow.ActualWidth - 80;
            //bte.Left = mainWindow.Left + (mainWindow.ActualWidth - bte.Width) / 2;
            //bte.Height = 100;
            //bte.Top = mainWindow.Top + mainWindow.ActualHeight - bte.Height - 86;//86包含状态条、滚动条的高度。

            //如果正在编辑的文本块被挡住，就自动向上滚动。
            //AutoScrollBaseText(bte);
            //}
            //} 
            #endregion

            bte.WindowStartupLocation = WindowStartupLocation.Manual;
            bte.Width = btx.Editor.BaseScrolledViewer.ActualWidth - 54;
            Point ptBase = new Point(0, 0);
            Point ptStart = btx.Editor.BaseScrolledViewer.PointToScreen(ptBase);
            bte.Left = ptStart.X + 26;
            bte.Height = 100;
            bte.Top = btx.Editor.BaseScrolledViewer.ActualHeight + ptStart.Y - 136;
            AutoScrollBaseText(bte);

            bte.fontSizeSlider.Value = mainWindow.fontSizeSlider.Value;
            bte.Owner = curEx.Editor.ParentWindow;

            if (newText == null)
            {
                if (editingCommentText)
                {
                    bte.inputTextBox.Text = btx.CommentText;
                }
                else
                {
                    bte.inputTextBox.Text = btx.ShowBackText ? btx.BackText : btx.Text;
                }

                bte.inputTextBox.SelectAll();
            }
            else
            {
                bte.inputTextBox.Text += newText;
                bte.inputTextBox.SelectionStart = bte.inputTextBox.Text.Length;
            }

            if (editingCommentText)
            {
                bte.editorTitle.Text = "文本块编辑器（备注文本）";
            }
            else
            {
                bte.editorTitle.Text = btx.ShowBackText ? "文本块编辑器（后台文本）" : "文本块编辑器";
            }

            if (bte.ShowDialog() == true)
            {
                #region 准备“撤销”与“重做”。
                if (mi == null)
                {
                    mi = new ModifingItem();

                    //加入“撤销”列表。
                    btx.Editor.Do(mi);
                }

                Action action = null;
                #endregion

                //改用TextBlock显示文本后，发现向字符(char)160,转换不但是没有必要的，且会造成文本显示不全。
                string resultString = bte.inputTextBox.Text.Replace((char)160, ' ');
                
                if (editingCommentText)
                {
                    action = new Action(btx.ExID, btx.ParentPanel.BasePanel.Children.IndexOf(btx),
                        typeof(Expressions.BaseText).Name, "CommentText", btx.CommentText, resultString);
                    btx.CommentText = resultString;
                    mi.Add(action);
                }
                else
                {
                    if (btx.ShowBackText)
                    {
                        action = new Action(btx.ExID, btx.ParentPanel.BasePanel.Children.IndexOf(btx),
                        typeof(Expressions.BaseText).Name, "BackText", btx.BackText, resultString);
                        btx.BackText = resultString;
                        mi.Add(action);
                    }
                    else
                    {
                        action = new Action(btx.ExID, btx.ParentPanel.BasePanel.Children.IndexOf(btx),
                           typeof(Expressions.BaseText).Name, "Text", btx.Text, resultString);
                        btx.Text = resultString;
                        mi.Add(action);
                    }
                }

                //btx.Editor.Do(mi);
                //这句不能再加，会重复的。因为调用本方法的时候已经调用过editor.Do(mi)了。
            }

            //尝试解决编辑文本块后显示不出来的问题。发现TabControl中的选项卡标头绘制也有问题。
            //实际上文本块的布局是没有问题的——用鼠标指针划过文本块就可以发现这一点。
            //造成这个Bug的原因可能是窗口焦点转移时未及时绘制。因为编辑器是另一个窗口。
            btx.Editor.InvalidateVisual();
            btx.Editor.UpdateLayout();
        }

        /// <summary>
        /// 在准备编辑内容前，尝试显示正在编辑的文本块——因为可能被挡住。
        /// 注意：这和“公式被选取”后不同——这里要考虑编辑器的位置。
        /// </summary>
        /// <param name="bte"></param>
        private static void AutoScrollBaseText(BaseTextEditor bte)
        {
            Globals.isDraging = false;
            if (Globals.dragSourceExpression != null) Globals.dragSourceExpression = null;

            double currentVOffcet = Globals.selectedEditor.BaseScrolledViewer.VerticalOffset;
            double currentHOffcet = Globals.selectedEditor.BaseScrolledViewer.HorizontalOffset;

            Point ptBase = new Point(0, 0);

            Point ptBaseText = Globals.selectedEditor.SelectedExpression.PointToScreen(ptBase);

            //如果太过靠下，被编辑器窗口挡住。
            if (ptBaseText.Y + Globals.selectedEditor.SelectedExpression.ActualHeight > bte.Top)
            {
                Globals.selectedEditor.BaseScrolledViewer.ScrollToVerticalOffset(
                    ptBaseText.Y + Globals.selectedEditor.SelectedExpression.ActualHeight
                    - bte.Top + currentVOffcet + 10);
            }

            Point ptScrollViewer = Globals.selectedEditor.BaseScrolledViewer.PointToScreen(ptBase);
            double rightOfScrollviewer = ptScrollViewer.X + Globals.selectedEditor.BaseScrolledViewer.ActualWidth;
            double rightOfBaseText = ptBaseText.X + Globals.selectedEditor.SelectedExpression.ActualWidth;
            if (rightOfBaseText > rightOfScrollviewer)
            {
                //如果右边不可见。
                Globals.selectedEditor.BaseScrolledViewer.ScrollToHorizontalOffset(currentHOffcet +
                    (rightOfBaseText - rightOfScrollviewer) + 30);
            }
            else
            {
                //如果左边不可见。
                if (ptScrollViewer.X > ptBaseText.X)
                {
                    Globals.selectedEditor.BaseScrolledViewer.ScrollToHorizontalOffset(currentHOffcet -
                        (ptScrollViewer.X - ptBaseText.X) - 10);
                }
            }
        }

        /// <summary>
        /// 清除文本。
        /// </summary>
        public static void BaseTextClearText()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.BaseText == false) return;

            Expressions.BaseText bt = curEx as Expressions.BaseText;

            #region 准备“撤销”与“重做”。
            ModifingItem mi = new ModifingItem();
            Action action = new Action(bt.ExID,
                bt.ParentPanel.BasePanel.Children.IndexOf(bt),
                typeof(Expressions.BaseText).Name, "Text", bt.Text, "");
            mi.Add(action);
            #endregion

            bt.Text = "";

            //加入“重做”列表。
            bt.Editor.Do(mi);
        }

        /// <summary>
        /// 复制文本。
        /// </summary>
        public static void BaseTextCopyText()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.BaseText == false) return;

            Expressions.BaseText bt = curEx as Expressions.BaseText;
            Clipboard.SetData(DataFormats.UnicodeText, bt.Text);
        }

        /// <summary>
        /// 追加粘贴。
        /// </summary>
        public static void BaseTextPasteAdd()
        {
            string text = Clipboard.GetText(TextDataFormat.UnicodeText);
            if (text == null || text.Length <= 0)
            {
                MessageBox.Show("剪贴板中无Unicode文本！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.BaseText == false) return;

            Expressions.BaseText bt = curEx as Expressions.BaseText;

            #region 准备“撤销”与“重做”。
            ModifingItem mi = new ModifingItem();
            Action action = new Action(bt.ExID,
                bt.ParentPanel.BasePanel.Children.IndexOf(bt),
                typeof(Expressions.BaseText).Name, "Text", bt.Text, bt.Text + text);
            mi.Add(action);
            #endregion

            bt.Text += text;

            //加入“重做”列表。
            bt.Editor.Do(mi);
        }

        /// <summary>
        /// 覆盖粘贴。
        /// </summary>
        public static void BaseTextPasteOverride()
        {
            string text = Clipboard.GetText(TextDataFormat.UnicodeText);
            if (text == null || text.Length <= 0)
            {
                MessageBox.Show("剪贴板中无Unicode文本！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.BaseText == false) return;

            Expressions.BaseText bt = curEx as Expressions.BaseText;

            #region 准备“撤销”与“重做”。
            ModifingItem mi = new ModifingItem();
            Action action = new Action(bt.ExID,
                bt.ParentPanel.BasePanel.Children.IndexOf(bt),
                typeof(Expressions.BaseText).Name, "Text", bt.Text, text);
            mi.Add(action);
            #endregion

            bt.Text = text;

            //加入“重做”列表。
            bt.Editor.Do(mi);
        }
    }
}
